package com.heaboy.emaidemo1.util;

import com.heaboy.emaidemo1.config.EmailServersConfig;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Properties;

@Component
public class MailSenderUtil {


    @Autowired
    private EmailServerSelector emailServerSelector;

    private Session getMailSession(EmailServersConfig.EmailServer server) {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.host", server.getHost());
        properties.setProperty("mail.port", server.getPort());
        properties.setProperty("mail.smtp.auth", server.getSmtpAuth());
        properties.setProperty("mail.smtp.ssl.enable", "true");
        properties.setProperty("mail.from", server.getUsername());
        properties.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");

        Authenticator authenticator = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(server.getUsername(), server.getPassword());
            }
        };

        Session session = Session.getDefaultInstance(properties, authenticator);
        session.setDebug(true);
        return session;
    }

    /**
     * 单个发送（使用轮询选中的邮箱）
     */
    public void sendMailTOSingleUser(String toEmailAddress, String title, String content) {
        EmailServersConfig.EmailServer server = emailServerSelector.getNextServer();
        // 打印认证账号和发件人地址
        System.out.println("认证账号：" + server.getUsername() + "，发件人地址：" + server.getUsername());

        Session session = getMailSession(server);
        try (Transport transport = session.getTransport("smtp")) {
            Message message = new MimeMessage(session);
            // 发件人地址与认证账号一致
            message.setFrom(new InternetAddress(server.getUsername()));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmailAddress));
            message.setSubject(title);
            message.setContent(content, "text/html;charset=UTF-8");

            transport.connect(
                    server.getHost(),
                    Integer.parseInt(server.getPort()),
                    server.getUsername(),
                    server.getPassword()
            );
            transport.sendMessage(message, message.getAllRecipients());
            System.out.println("发送成功！使用邮箱：" + server.getUsername());
        } catch (MessagingException e) {
            System.err.println("发送失败！使用邮箱：" + server.getUsername() + "，错误：" + e.getMessage());
            e.printStackTrace();
        }
    }

}